﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace VsSourceCpoy.Helper
{
    public class FileCopyHelper
    {
        public Action<string,string> CopyListener { get; set; }
        public bool Copy(string fromPath, string toPath, bool overwrite)
        {
            try
            {
                DirectoryInfo di = new DirectoryInfo(toPath.Substring(0, toPath.LastIndexOf("\\")));
                if (!di.Exists)
                {
                    di.Create();
                }
                if (CopyListener != null)
                    CopyListener(fromPath, toPath);
                File.Copy(fromPath, toPath, overwrite);
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }

        public int CopyDir(string fromPath, string toPath, bool overwrite)
        {
            return CopyDir(fromPath, toPath, overwrite, null, null);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fromPath"></param>
        /// <param name="toPath"></param>
        /// <param name="overwrite"></param>
        /// <param name="dirFilter">dirFilter如果返回true，则拷贝，否则忽略</param>
        /// <param name="fileFilter">fileFilter如果返回true，则拷贝，否则忽略</param>
        /// <returns></returns>
        public int CopyDir(string fromPath, string toPath, bool overwrite, Func<DirectoryInfo, bool> dirFilter, Func<FileInfo, bool> fileFilter)
        {
            DirectoryInfo difrom = new DirectoryInfo(fromPath);
            DirectoryInfo dito = new DirectoryInfo(toPath);
            if (!difrom.Exists)
            {
                throw new ArgumentException("Path '" + fromPath + "' is not a vaild directory!");
            }
            if (!dito.Exists)
            {
                dito.Create();
            }
            FileInfo[] fiFrom = difrom.GetFiles();
            foreach (var item in fiFrom)
            {
                string toFileName = Path.Combine(dito.FullName, item.Name);
                if (fileFilter != null && !fileFilter(item))
                {
                    continue;

                }
                else
                {
                    Copy(item.FullName, toFileName, overwrite);
                }
            }
            DirectoryInfo[] dirFrom = difrom.GetDirectories();
            foreach (var item in dirFrom)
            {
                string toDirName = Path.Combine(dito.FullName, item.Name);
                if (dirFilter != null && !dirFilter(item))
                {
                    continue;
                }
                else
                {
                    CopyDir(item.FullName, toDirName, overwrite, dirFilter, fileFilter);
                }
            }
            return 1;
        }
    }
}
